<template>
  <el-card class="info-card">
    <div class="card-header">
      <h1>用户个人信息管理</h1>
    </div>

    <div class="form-container">
      <el-form :model="formData" label-width="120px" :rules="rules" ref="formRef">
        <el-row :gutter="20">
          <!-- 左侧表单 -->
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="formData.realName" placeholder="请输入真实姓名" />
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="formData.gender">
                <el-radio label="0">女</el-radio>
                <el-radio label="1">男</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker
                  v-model="formData.birthDate"
                  type="date"
                  placeholder="请选择出生日期"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="知识等级" prop="knowledgeLevel">
              <el-select v-model="formData.knowledgeLevel" placeholder="请选择知识等级" style="width: 100%">
                <el-option label="初学者" value="0" />
                <el-option label="爱好者" value="1" />
                <el-option label="专家" value="2" />
                <el-option label="研究人员" value="3" />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 右侧头像上传 -->
          <el-col :span="12">
            <el-form-item label="头像上传" prop="avatarUrl">
              <el-upload
                  class="avatar-uploader"
                  action="http://localhost:88/File/upImg"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
              >
                <!-- 显示头像或 + 图标 -->
                <img v-if="formData.avatarUrl" :src="formData.avatarUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="savePersonalInfo">保存信息</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import userApi from '../../apis/UserApi.js' // 导入 userApi
import { ElMessage } from 'element-plus'

const formData = ref({
  realName: '',
  gender: '',
  birthDate: '',
  knowledgeLevel: '',
  avatarUrl: '' // 初始为空
})

// 表单验证规则
const rules = {
  realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  birthDate: [{ required: true, message: '请选择出生日期', trigger: 'change' }],
  knowledgeLevel: [{ required: true, message: '请选择知识等级', trigger: 'change' }]
}

// 头像上传成功回调
const handleAvatarSuccess = (response) => {
  if (response.code === 200 && response.data) {
    formData.value.avatarUrl = response.data
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error('头像上传失败: ' + (response.message || '未知错误'))
  }
}

// 上传前验证
const beforeAvatarUpload = (file) => {
  const isValidType = ['image/jpeg', 'image/png'].includes(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isValidType) {
    ElMessage.error('只能上传 JPG/PNG 格式图片')
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB')
  }
  return isValidType && isLt2M
}

// 保存个人信息
const savePersonalInfo = async () => {
  try {
    const res = await userApi.SaveSelfInformation(formData.value)
    if (res.code === 200) {
      ElMessage.success('保存成功')
    } else {
      ElMessage.error('保存失败: ' + res.message)
    }
  } catch (error) {
    ElMessage.error('保存失败，请稍后再试')
  }
}

// 获取个人信息
const fetchPersonalInfo = async () => {
  try {
    const res = await userApi.ViewSelfInformation()
    if (res.code === 200) {
      Object.assign(formData.value, res.data)
    } else {
      ElMessage.error('加载失败: ' + res.message)
    }
  } catch (error) {
    ElMessage.error('加载失败，请稍后再试')
  }
}

onMounted(() => {
  fetchPersonalInfo()
})
</script>

<style scoped>
.info-card {
  margin: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  background-color: #e6f7d8; /* 绿色背景 */
}

.card-header {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.form-container {
  padding: 20px;
}

.avatar-uploader {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
